package org.person.gift.listener;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.person.gift.constans.BaseConstants;
import org.person.gift.doc.GiftSpuDoc;
import org.person.gift.service.IGiftSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 消费者监听
 */
@Component
@RocketMQMessageListener(topic = BaseConstants.GIFT_ONSALE_TX_TOPIC,
        selectorExpression=BaseConstants.GIFT_ONSALE_TX_TAG
        ,consumerGroup = BaseConstants.GIFT_ONSALE_TX_CONSUMER_GROUP)
@Slf4j
public class GiftOnsaleMQListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IGiftSpuService giftSpuService;

    @Override
    public void onMessage(MessageExt messageExt) {

        try {
            byte[] body = messageExt.getBody();
            String jsonStr = new String(body, "utf8");
            log.info(jsonStr);
            //转换为doc
            List<GiftSpuDoc> giftDocs = JSONArray.parseArray(jsonStr, GiftSpuDoc.class);
            //保存doc
            giftSpuService.onsale(giftDocs);
        } catch (Exception e) {
            e.printStackTrace();
            //要抛出异常,抛出异常后就给你消费不成功
            throw new RuntimeException("消费失败!");
        }
    }
}
